from PIL import Image
import numpy as np

image_path = "images/mario.bmp"
try:
    # 打开图片并验证
    image = Image.open(image_path)
    print(f"成功读取图片: {image_path}")
    print(f"图片格式: {image.format}, 尺寸: {image.size}, 模式: {image.mode}")
    
    # 转换为RGB并查看部分像素
    image_rgb = image.convert("RGB")
    image_array = np.array(image_rgb)
    pixels = image_array.reshape(-1, 3)
    print("\n前10个像素的RGB值:")
    for i, pixel in enumerate(pixels[:10]):
        print(f"像素{i}: R={pixel[0]}, G={pixel[1]}, B={pixel[2]}")
    
    # 计算出现次数最多的颜色
    unique_colors, counts = np.unique(pixels, axis=0, return_counts=True)
    background_color = unique_colors[counts.argmax()]
    print(f"\n出现次数最多的颜色（背景色）: R={background_color[0]}, G={background_color[1]}, B={background_color[2]}")
    print(f"该颜色出现次数: {counts.max()}")

except FileNotFoundError:
    print(f"错误：未找到图片文件 {image_path}")
except Exception as e:
    print(f"处理图片时出错: {e}")
